WhatIf and Confirm

PowerShell's WhatIf and confirm are two great commands for testing complicated scripts without risking the code running amok. For example, if you decide to delete files by using a script containing wildcards, there could be all manner of unexpected side effects. By employing PowerShell, and appending the -WhatIf switch, you get a preview of would happen without risking any damage.


PowerShell -WhatIf Example

By adding -WhatIf at the end of the command we are saying to PowerShell: 'Just test, don't actually make any permanent changes'. Please note, there could be serious consequences if you don't use the -WhatIf switch. If you don't understand what you are doing, you could delete all your .txt files.

# PowerShell -WhatIf safety parameter Clear-Host Get-Childitem C:\SomeFile\*.txt -Recurse | Remove-Item -WhatIf

PowerShell -Confirm Example

Here is another PowerShell parameter that you append to a 'normal' script - confirm. It really is a case of confirm by name, and confirm by nature. PowerShell says to you: 'Do you really want to do this?'.

# PowerShell -Confirm parameter Get-Childitem C:\Dzxocs\*.* -Include *.txt -Recurse | Remove-Item -Confirm

-Confirm:$false

if you are running scripts which require a response, then you could try appending -Confirm:False (do remember that colon).

# PowerShell -Confirm for unattended machines Restart-Service Bits -Confirm:$False